<template>
  <div
      class="diy_edit classification_information_edits page_classification_information"
      id="classification_information_edit"
  >
    <el-form
        :model="form"
        ref="ruleFormRef" 
		:rules="rules"
        label-width="auto"
        class="edit_classification_information_form"
        size="large"
    >
      <el-row class="row_e">
          <el-col v-if="$check_field('ger','classification_name','/classification_information/view') || $check_field('add','classification_name','/classification_information/view') || $check_field('set','classification_name','/classification_information/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="分类名称" prop="classification_name">
                      <el-input id="classification_name" v-model="form['classification_name']" placeholder="请输入分类名称"
                      v-if="(form['classification_information_id'] && $check_field('set','classification_name','/classification_information/view')) || (!form['classification_information_id'] && $check_field('add','classification_name','/classification_information/view'))" :disabled="disabledObj['classification_name_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','classification_name','/classification_information/view')">{{form['classification_name']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','description_and_explanation','/classification_information/view') || $check_field('add','description_and_explanation','/classification_information/view') || $check_field('set','description_and_explanation','/classification_information/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="描述说明" prop="description_and_explanation">
                      <el-input id="description_and_explanation" v-model="form['description_and_explanation']" placeholder="请输入描述说明"
                      v-if="(form['classification_information_id'] && $check_field('set','description_and_explanation','/classification_information/view')) || (!form['classification_information_id'] && $check_field('add','description_and_explanation','/classification_information/view'))" :disabled="disabledObj['description_and_explanation_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','description_and_explanation','/classification_information/view')">{{form['description_and_explanation']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','location_information','/classification_information/view') || $check_field('add','location_information','/classification_information/view') || $check_field('set','location_information','/classification_information/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="地点信息" prop="location_information">
                      <el-input id="location_information" v-model="form['location_information']" placeholder="请输入地点信息"
                      v-if="(form['classification_information_id'] && $check_field('set','location_information','/classification_information/view')) || (!form['classification_information_id'] && $check_field('add','location_information','/classification_information/view'))" :disabled="disabledObj['location_information_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','location_information','/classification_information/view')">{{form['location_information']}}</div>
                    </el-form-item>
        </el-col>
          <el-col v-if="$check_action('/classification_information/view', 'set') || $check_action('/classification_information/view', 'add')"
          :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
            <el-form-item label="当前位置" prop="location_address">
              <el-input style="width: 80%" id="location_address" v-model="form['location_address']" :disabled="true"></el-input>
              <el-button size="mini" @click="getLongitudeLatitude()">定位</el-button>
            </el-form-item>
        </el-col>
      </el-row>
      <div v-if="$check_action('/classification_information/view','set') || $check_action('/classification_information/view','add') || $check_option('/classification_information/table','examine')" class="footer">
        <el-button type="primary" @click="onSubmit" size="large">提交</el-button>
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
      <div v-else class="footer">
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
  import {ElMessage} from "element-plus";
  import {ref, onMounted} from "vue";
  import { $post, $get } from "@/api/Api.js";
  import storageHelper from "@/libs/StorageHelper";
  import {useStore} from "vuex";
  import { useRouter, useRoute } from "vue-router";
  import {
          $check_field,
          $fullUrl,
          $banseUrl,
          $check_action,
          $getUrlParams,
          filterSensitiveWords,
          $get_stamp,
          $get_rand,
          $toTime,
          $push
  } from "@/utils/utils.js";

  let router = useRouter();
  let route = useRoute();
  let store = useStore();
  let token = storageHelper.getToken() || null;
  let UserInfo = storageHelper.getUserInfo();
  let user_id = storageHelper.getUserInfo().user_id;
  let user_group = storageHelper.getUserInfo().user_group;
  let classification_information_id = $getUrlParams().classification_information_id;
  let url_add = ref("/api/classification_information/add");
  let url_set = ref("/api/classification_information/set");
  let field = ref("classification_information_id")
  let url_get_obj = ref("/api/classification_information/get_obj");
  let url_upload = ref("/api/classification_information/upload");
  let ruleFormRef = ref(null);
  
  let rules = ref({
			  });

  let disabledObj = ref({
      "classification_name_isDisabled": false,
        "description_and_explanation_isDisabled": false,
        "location_information_isDisabled": false,
    });
  let form = ref({
    "classification_name":  '', // 分类名称
      "description_and_explanation":  '', // 描述说明
      "location_information":  '', // 地点信息
      "classification_information_id": 0, // ID
    "location_address": "", // 定位地址
    "location_lng": "", // 定位地址经度
    "location_lat": "", // 定位地址纬度
  });
  
    
    
                                                                  let getLongitudeLatitude = () => {
      form.value.location_address = "广东省深圳市南山区科技园";
      form.value.location_lng = "113.946782";
      form.value.location_lat = "22.556481";
      //如果该对象存在，那么地理位置服务可用。
      if ("geolocation" in navigator) {
        /* 地理位置服务可用 */
        let options = {
          enableHighAccuracy: true, //布尔值，表示系统是否使用最高精度来表示结果，注意，这会导致较慢的响应时间或者增加电量消耗（比如对于支持gps的移动设备来说）。如果值为false ，设备会通过更快响应以及/或者使用更少的电量等方法来尽可能的节约资源。默认值fasle
          timeout: 5000, //它表明的是设备必须在多长时间（单位毫秒）内返回一个位置。默认直到获取到位置才会返回值。
          maximumAge: 0, //表明可以返回多长时间（即最长年龄，单位毫秒）内的可获取的缓存位置。如果设置为 0, 说明设备不能使用一个缓存位置，而且必须去获取一个真实的当前位置。默认0
        };
        function success(position) {
          //position.coords (只读) 返回一个定义了当前位置的Coordinates对象。
          //position.timestamp (只读) 返回一个时间戳DOMTimeStamp， 这个时间戳表示获取到的位置的时间。
          let lat = position.coords.latitude; //当前位置的纬度
          let lng = position.coords.longitude; //当前位置精度
          let location = lng + "," + lat;
          let url =
              "http://restapi.amap.com/v3/geocode/regeo?key=b6eb2819a6ba4c5119591614272fe7ca&location=" +
              location;
                $get(url).then((res) => {
            if (res.status === 200) {
              let data = res.data;
              if (data.status === "1") {
                form.value.location_address = data.regeocode.formatted_address;
                form.value.location_lng = JSON.stringify(lng);
                form.value.location_lat = JSON.stringify(lat);
              } else {
                console.log(data.info);
              }
            }
          })
              .catch((res) => {
                console.log(res);
              });
        }
        function error(err) {
          let errorType = [
            "您拒绝共享位置信息",
            "获取不到位置信息",
            "获取位置信息超时",
          ];
          console.log(errorType[err.code - 1]);
        }
        navigator.geolocation.getCurrentPosition(success, error, options);
      } else {
        /* 地理位置服务不可用 */
        console.log("无法获取您的位置，请检查定位是否开启或刷新重试");
      }
    };
  //提交前验证事件
  let submit_check = () => {
                          };
  // 点击取消
  let cancel = () => {
    router.go(-1);
  };
  // 点击提交
  let onSubmit = async () => {
    let valid = await ruleFormRef.value.validate();
    if (valid) {
      // 提交表单
      if (classification_information_id) {
        // 编辑
        delete form.value.update_time;
              $post(url_set.value + "?classification_information_id=" + classification_information_id, form.value).then((res) => {
          if (res.result) {
          router.push("/home/classification_information/table");
          ElMessage.success("提交成功！");
          } else if (res.error) {
            ElMessage.error(res.error.message);
          }
        });

      } else {
        // 新增
              $post(url_add.value, form.value).then((res) => {
          if (res.result) {
              router.push("/home/classification_information/table");
              ElMessage.success("提交成功！");
          } else if (res.error) {
            ElMessage.error(res.error.message);
          }
        });

      }
    } else {
      ElMessage.error(msg);
    }
  };
  // 查询数组对象某个是否包含某个值,返回对应对象
  let getObj = (arr, val) => {
    let obj = arr.find((item) => item.user_id == val);
    let ret = "";
    if (obj) {
      if (obj.nickname) {
        ret = obj.nickname;
      } else {
        ret = obj.username;
      }
    }
    return ret;
  };
  //获取对象之前
  let get_obj_before = (param) => {
    var formArr = "";
                                  if(form.value && formArr){
      Object.keys(form.value).forEach(key => {
        Object.keys(formArr).forEach(dbKey => {
          if(key === dbKey){
            disabledObj.value[key+'_isDisabled'] = true;
          }
        })
      })
    }
                localStorage.removeItem('form')
    return param;
  }
  // js判断字段是否是时间戳格式
  let isTimestamp = (value) => {
    return /^\d{10}$/.test(value) || /^\d{13}$/.test(value);
  }
  //获取对象之后
  let get_obj_after = (json, func) => {
                                                                                              }
  let is_view = () => {
    var bl = user_group == "管理员";
    if (!bl) {
      bl = $check_action('/classification_information/table', 'add');
      console.log(bl ? "你有表格添加权限视作有添加权限" : "你没有表格添加权限");
    }
    if (!bl) {
      bl = $check_action('/classification_information/table', 'set');
      console.log(bl ? "你有表格添加权限视作有修改权限" : "你没有表格修改权限");
    }
    if (!bl) {
      bl = $check_action('/classification_information/view', 'add');
      console.log(bl ? "你有视图添加权限视作有添加权限" : "你没有视图添加权限");
    }
    if (!bl) {
      bl = $check_action('/classification_information/view', 'set');
      console.log(bl ? "你有视图修改权限视作有修改权限" : "你没有视图修改权限");
    }
    if (!bl) {
      bl = $check_action('/classification_information/view', 'get');
      console.log(bl ? "你有视图查询权限视作有查询权限" : "你没有视图查询权限");
    }
    console.log(bl ? "具有当前页面的查看权，请注意这不代表你有字段的查看权" : "无权查看当前页，请注意即便有字段查询权限没有页面查询权限也不行");
    return bl;
  }
  // 获取详情
  let get_classification_information_obj = async () => {
    let list = await $get("/api/classification_information/get_obj?classification_information_id=" + classification_information_id);
    form.value = list.result.obj;
    get_obj_after();
  };
  onMounted(() => {
                if (classification_information_id) {
      get_classification_information_obj();
    }else {
      get_obj_before();
      get_obj_after();
    }

  });
</script>

<style scoped lang="less">
  .diy_edit {
    width: 100%;

    .edit_classification_information_form {
      max-width: 80%;
      margin: 90px auto;

      .fn {
        width: 100%;
      }
    }

    img {
      width: 100px;
      height: 100px;
    }

    .edit_list_classification_information_sell {
      width: 80%;
      margin: 90px auto;
    }

    .footer {
      text-align: center;
    }
  }
</style>
  